<!-- 诉讼申请单 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="handlerId" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.handlerId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.handlerId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="handlerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.handlerDeptId"
            :departName="model.handlerDeptIdText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.handlerDeptIdText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="项目名称" prop="projectId" required>
          <h-select-project-input-popup
            :api="queryDistributionProjectList"
            :proDisabled="true"
            :projectStatus="'2'"
            ref="projectSelect"
            v-model="model.projectId"
            style="width: 100%"
            placeholder="请选择项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-project-input-popup>
          <!-- @change="projectChangeHandle" -->
        </u-form-item>
        <u-form-item label="经营团队" prop="teamName" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.teamName"
            objectField="model.teamName"
            placeholder="请选择经营团队"
            :tdlx="1"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          />
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">费用信息</view>
        <ManageclearingFormInfo :dictOptions="dictOptions" :entities="ManageclearingDs" />
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">任务附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.file" :isIcon="false"></h-upload-file>
          <file-list v-if="model.file" v-model="model.file" :isDelete="true"></file-list>
        </view>
      </view>
      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
      <u-toast ref="uToast"></u-toast>
      <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
    </u-form>
  </view>
</template>
    
    <script>
import { mapState } from 'vuex'
import moment from 'moment'
// import Decimal from 'decimal.js'
import {
  gainBillNo,
  add,
  edit,
  info,
  queryContractFinal,
  queryProjectTaskList,
  queryProgressPaymentNode,
  queryErpAuditManageClearingDetail,
} from '@/api/audit/ManageclearingForm.js'
import { queryDistributionProjectList } from '@/api/index'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import fileList from '@/pages/synergy/components/fileList.vue'
import ManageclearingFormInfo from './components/ManageclearingFormInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗

export default {
  name: 'manageclearingForm',
  components: {
    fileList,
    ManageclearingFormInfo,
    ProcessNodeConfiguration,
  },
  data() {
    return {
      queryDistributionProjectList,
      isSubmit: false, // 控制按钮是否可以点击
      index: null,
      showFormModal: false,
      loading: false,
      id: '',
      basicForm: {},
      dictOptions: {},
      formData: [],
      ManageclearingDs: [],
      model: {
        bpmBizTitle: '',
        billNo: '',
        createTime: '',
        handlerId: '',
        handlerDeptId: '',
        projectId: '',
        teamName: '',
        file: null,
      },
      rules: {
        billNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
        handlerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
        handlerId: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
        createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        projectId: [{ required: true, message: '请选择项目名称!', trigger: ['blur', 'change'] }],
        teamName: [{ required: true, message: '请选择经营团队!', trigger: ['blur', 'change'] }],
      },
      projectLeadingToSubTable: '',
      projectLeadingToSubTableText: '',
      projectIdBackups: null,
      //代码生成后需手动设置流程编码
      flowCode: 'onl_erp_audit_manage_clearing',
      formUrl: '/erp/audit/manage/modules/ErpAuditManageClearingForm',
      formUrlMobile: '/pages/synergy/ErpAuditManageClearingForm',
      beanName: 'ErpManageClearingFlow',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
      this.initDataList()
      // this.initDisclaimerDetailList()
    } else {
      this.initForm()
      this.initBillNo()
    }
    this.initDictConfig()
  },
  onReady() {
    this.$refs.projectSelect.$on('change', (event) => {
      this.projectChangeHandle(event)
    })
  },
  onUnload() {
    this.$off('change')
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },

    // 清空自动带出的字段
    resetAutoFields() {
      this.$set(this.model, 'teamName', null)
      this.ManageclearingDs = []
    },

    async projectChangeHandle(data) {
      if (!data) {
        return
      }
      // 先清空自动带出的字段
      this.resetAutoFields()
      let project = data
      this.$set(this.model, 'projectName', project.projectName)
      // teamName 经营团队
      this.$set(this.model, 'teamName', project.teamName)
      // 查合同
      await queryContractFinal({ xmmc: this.model.projectId, htlx: 1 }).then(async (res) => {
        if (res.success && !!res.result && !!res.result.records[0]) {
          this.$set(this.model, 'contractId', res.result.records[0].id)
          this.$set(this.model, 'contractName', res.result.records[0].htmc)
          await queryProgressPaymentNode({ contractId: this.model.contractId }).then((res) => {
            if (res.success) {
              if (res.result.length > 0) {
                res.result.forEach((item) => {
                  let manageMoney = null
                  if (item.realCollectionPaymentMoney != null) {
                    manageMoney = item.realCollectionPaymentMoney * 0.2
                    manageMoney = manageMoney.toFixed(2)
                  }
                  let node = {
                    paymentNodeName: item.nodeName,
                    paymentMoney: item.paymentMoney,
                    realCollectionPaymentMoney: item.realCollectionPaymentMoney,
                    manageMoney: manageMoney,
                  }
                  this.ManageclearingDs.push(node)
                })
              }
            }
          })
        }
      })
    },
    initDictConfig() {
      // initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'teamId', res.result)
      //   }
      // })
      // initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'categoryName', res.result)
      //   }
      // })
      // initDictOptions('erp_employee_file,name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'empId', res.result)
      //   }
      // })
      initDictOptions('erp_omc_project,project_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'projectId', res.result)
        }
      })
      // //款项名称
      // initDictOptions('erp_progress_payment_node,node_name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'paymentName', res.result)
      //   }
      // })
      // //豁免类型
      // initDictOptions('exemption_type').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'exemptionType', res.result)
      //   }
      // })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
      //   this.calculateTotalAmount(this.formData)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    // 新增物料
    handleAddMember() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({})
      this.model.billNo = res.result
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.handlerId = this.userInfo.empId //当前登录人
      this.model.handlerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    //查询任务信息子表数据
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
      this.projectIdBackups = this.model.projectId
    },
    //查询任务信息子表数据
    async initDataList() {
      const response = await queryErpAuditManageClearingDetail({ mainId: this.id, pageSize: 999 })
      const data = response.success ? response.result.records : []
      this.ManageclearingDs = data
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (!this.ManageclearingDs.length) {
          this.$u.toast('费用信息不能为空!')
          return Promise.reject('费用信息不能为空!')
        }
        return Promise.resolve()
      })
    },
    getCreateTime() {
      let createTime = this.model.createTime
      let date = createTime.substring(0, 10)
      return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
    },
    setBpmBizTitle() {
      // 标题 表单名称+项目名称+发起人+申请日期
      let date = this.getCreateTime()
      let projectName = filterMultiDictText(this.dictOptions['projectId'], this.model.projectId + '')
      this.model.bpmBizTitle = '管理结算费用单' + '-' + (projectName? projectName + '-':'') + this.userInfo?.employee?.name + '-' + date
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      this.setBpmBizTitle()
      // 子表
      this.model.detailList = this.ManageclearingDs
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          // var that = this
          this.isSubmit = true
          // 获取流程列表
          if (this.model.id) {
            this.getProcessList(this.model.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      this.setBpmBizTitle()
      // 子表
      this.model.detailList = this.ManageclearingDs
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.isSubmit = true
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home',
                })
              }
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
  }
}
</script>
    
    <style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
    